package com.service.Impl;

import com.exception.BusinessException;
import com.mapper.AddressMapper;
import com.pojo.Address;
import com.service.AddressService;
import io.micrometer.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class AddressServiceImpl implements AddressService {
    @Autowired
    private AddressMapper addressMapper;

    /**
     * 校验手机格式
     * @param phone
     * @return
     */
    private boolean isValidPhone(String phone) {
        return phone != null && phone.matches("^1[3-9]\\d{9}$");
    }
    @Override
    public void deleteById(Integer addressId) {
        // 1. 参数校验
        if (addressId == null || addressId <= 0) {
            throw new IllegalArgumentException("地址ID不合法");
        }
        // 2. 检查地址是否存在
        Address address = addressMapper.selectById(addressId);
        if (address == null) {
            throw new BusinessException("地址不存在或已被删除");
        }

        // 4. 执行删除
        addressMapper.deleteById(addressId);
        log.info("地址删除成功，ID：{}", addressId);

    }
    @Override
    public void add(Address address) {
        // 校验参数
        if (address == null) {
            throw new IllegalArgumentException("地址信息不能为空");
        }
        if (address.getAddressUser() == null || address.getAddressUser() <= 0) {
            throw new IllegalArgumentException("用户ID不合法");
        }
        if (!isValidPhone(address.getConsigneePhone())) {
            throw new IllegalArgumentException("手机号格式不正确");
        }
        if (StringUtils.isBlank(address.getConsigneeName())) {
            throw new IllegalArgumentException("收货人姓名不能为空");
        }
        addressMapper.add(address);
        log.info("地址添加成功，ID：{}，用户：{}", address.getAddressId(), address.getAddressUser());
    }
}
